﻿<%@ Page Language="C#" MasterPageFile="main.master" Inherits="VioletDevelopmentLaboratory.Net.Web.PageBase" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Web.Configuration" %>

<script runat="server">

	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			Authorization_Bind();

			Role_Bind();

			Config_DataBind();

			ConnectionStringNameDropDownList_DataBind();

			ControlSettingGridView_Bind();
		}
	}

	protected void Authorization_Bind()
	{		
		Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~/vboard/manager");

		AuthorizationSection authorization = (AuthorizationSection)webConfig.GetSection("system.web/authorization");

		GridView1.DataSource = authorization.Rules;
		GridView1.DataBind();
	}

	protected void Role_Bind()
	{
		if (Roles.Enabled)
		{
			RoleDropDownList.DataSource = Roles.GetAllRoles();
			RoleDropDownList.DataBind();

			RoleDropDownList.Items.Insert(0, new ListItem("-Select-", ""));
			RoleDropDownList.Items.Insert(1, new ListItem("-none-", ""));
		}
	}

	protected void ConnectionStringNameDropDownList_DataBind()
	{
		ConnectionStringNameDropDownList.DataSource = ConfigurationManager.ConnectionStrings;
		ConnectionStringNameDropDownList.DataTextField = "Name";
		ConnectionStringNameDropDownList.DataValueField = "Name";
		ConnectionStringNameDropDownList.DataBind();

		ConnectionStringNameDropDownList.Items.Insert(0, new ListItem("-Select-", ""));
	}

	protected void ConnectionStringNameDropDownList_SelectedIndexChanged(object sender, EventArgs e)
	{
		ConnectionStringNameTextBox.Text = ConnectionStringNameDropDownList.SelectedValue;
	}

	protected void Config_DataBind()
	{
		RootLabel.Text = VUtility.WebApplicationPhysicalPath;

		ApplicationNameTextBox.Text = VWebConfigurationReader.ApplicationName;
		ConnectionStringNameTextBox.Text = VWebConfigurationReader.ConnectionStringName;

		FileFolderTextBox.Text = VWebConfigurationReader.Path.FileFolder;
		MemberPictureFolderTextBox.Text = VWebConfigurationReader.Path.MemberPictureFolder;
		ExceptionLogFolderTextBox.Text = VWebConfigurationReader.Path.ExceptionLogFolder;

		AdministratorRoleNameTextBox.Text = VWebConfigurationReader.Administrator.Role;
		AdministratorNamesTextBox.Text = VWebConfigurationReader.Administrator.Names;
		AdministratorEmailTextBox.Text = VWebConfigurationReader.Administrator.Email;
		PublicationReportCheckBox.Checked = VWebConfigurationReader.Administrator.PublicationReport;
	}

	protected void UpdateSectionButton_Click(object sender, EventArgs e)
	{
		VWebConfigurationManager manager = new VWebConfigurationManager();
		manager.Section.ApplicationName = ApplicationNameTextBox.Text;
		manager.Section.ConnectionStringName = ConnectionStringNameTextBox.Text;

		manager.Section.Administrator.Email = AdministratorEmailTextBox.Text;
		manager.Section.Administrator.Names = AdministratorNamesTextBox.Text.Trim();
		manager.Section.Administrator.Role = AdministratorRoleNameTextBox.Text.Trim();
		manager.Section.Administrator.PublicationReport = PublicationReportCheckBox.Checked;

		manager.Save();

		Configuration webConfig = WebConfigurationManager.OpenWebConfiguration("~/vboard/manager");

		AuthorizationSection authorization = (AuthorizationSection)webConfig.GetSection("system.web/authorization");

		authorization.Rules.Clear();

		AuthorizationRule allowRule = new AuthorizationRule(AuthorizationRuleAction.Allow);
		allowRule.Users.AddRange(AdministratorNamesTextBox.Text.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
		allowRule.Roles.Add(AdministratorRoleNameTextBox.Text);
		authorization.Rules.Add(allowRule);

		AuthorizationRule dennyRule = new AuthorizationRule(AuthorizationRuleAction.Deny);
		dennyRule.Users.Add("*");
		authorization.Rules.Add(dennyRule);

		webConfig.Save();

		Response.Redirect(Request.RawUrl);
	}

	protected void ControlSettingGridView_Bind()
	{
		ControlSettingGridView.DataSource = VWebConfigurationReader.ControlSettings;
		ControlSettingGridView.DataBind();
	}
	protected void ControlSettingGridView_RowEditing(object sender, GridViewEditEventArgs e)
	{
		ControlSettingGridView.EditIndex = e.NewEditIndex;
		ControlSettingGridView_Bind();
	}

	protected void ControlSettingGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
	{
		ControlSettingGridView.EditIndex = -1;
		ControlSettingGridView_Bind();
	}

	protected void ControlSettingGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
	{
		VWebConfigurationManager manager = new VWebConfigurationManager();
		manager.Section.ControlSettings[ControlSettingGridView.DataKeys[e.RowIndex].Value.ToString()].Value =
			((TextBox)ControlSettingGridView.Rows[e.RowIndex].FindControl("ValueTextBox")).Text;
		manager.Save();

		Response.Redirect(Request.RawUrl);
	}

	protected void ControlSettingGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
	{
		VWebConfigurationManager manager = new VWebConfigurationManager();
		manager.Section.ControlSettings.Remove(ControlSettingGridView.DataKeys[e.RowIndex].Value.ToString());
		manager.Save();

		Response.Redirect(Request.RawUrl);
	}

	protected void AddControlSettingButton_Click(object sender, EventArgs e)
	{
		VWebConfigurationManager manager = new VWebConfigurationManager();
		manager.Section.ControlSettings.Add(PropertyTextBox.Text, ValueTextBox.Text);
		manager.Save();

		Response.Redirect(Request.RawUrl);
	}

	protected void RoleDropDownList_SelectedIndexChanged(object sender, EventArgs e)
	{
		AdministratorRoleNameTextBox.Text = RoleDropDownList.SelectedValue;
	}
</script>

<asp:Content ContentPlaceHolderID="BodyContentPlaceHolder" ID="Content1" runat="server">
	<h2>구성 설정</h2>

	<p>구성 설정에 앞서 현재 로그인한 계정이 관리자 권한을 가지는지 확인하시기 바랍니다.
	만약 현재 로그인한 계정이 관리자 권한에 해당되지 않는 상황에서 접속 설정으로 하면 VWeb Manager에 접속할 수 없게 됩니다.
	그럴경우에는 vboard/manager/web.config파일을 직접 수정해야합니다.</p>

	<p>관리자는 역할(Role)과 아이디(Name)로 설정할 수 있습니다.</p>

	<p>웹사이트가 RoleProvider를 사용하는 경우에는 먼저 Membership메뉴로 이동하여 해당 계정에 관리자 역할을 부여한 후에 진행하십시오.</p>

	<p>웹사이트가 RoleProvider를 사용하지 않는 경우에는 관리자로 사용할 로그인 계정 이름을 확인하고 진행하십시오.</p>

	<fieldset>
		<legend>현재 VWeb Manager 접속 권한</legend>
		<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
			<Columns>
				<asp:TemplateField HeaderText="Users">
					<ItemTemplate><%# Eval("Users") %></ItemTemplate>
				</asp:TemplateField>
				<asp:TemplateField HeaderText="Roles">
					<ItemTemplate><%# Eval("Roles") %></ItemTemplate>
				</asp:TemplateField>
				<asp:TemplateField HeaderText="Action">
					<ItemTemplate><%# Eval("Action") %></ItemTemplate>
				</asp:TemplateField>
			</Columns>
		</asp:GridView>
	</fieldset>

	<hr />

	<fieldset>
		<legend>기본</legend>
		<div class="Field">
			<div class="FieldName">ApplicationName</div>
			<div class="FieldValue">
				<asp:TextBox ID="ApplicationNameTextBox" runat="server" />
				<div>*웹어플리케이션 이름을 설정합니다. 이 설정은 최초 설정후 변경하지 마십시오.</div>
			</div>
			<div class="Clear"></div>
		</div>
		<div class="Field">
			<div class="FieldName">ConnectionStringName</div>
			<div class="FieldValue">
				<asp:TextBox ID="ConnectionStringNameTextBox" runat="server" Columns="35" ReadOnly="true" ValidationGroup="VWeb" />
				<asp:DropDownList ID="ConnectionStringNameDropDownList" runat="server" ValidationGroup="VWeb"
					onselectedindexchanged="ConnectionStringNameDropDownList_SelectedIndexChanged" 
					AutoPostBack="True" />
				<asp:RequiredFieldValidator ID="ConnectionStringNameTextBoxRequiredFieldValidator" 
					runat="server" ControlToValidate="ConnectionStringNameTextBox" ValidationGroup="VWeb"
					Display="Dynamic" ErrorMessage="*" />
				<div>*DB연결 문자열을 설정합니다.</div>
			</div>
			<div class="Clear"></div>
		</div>
	</fieldset>

	<fieldset>
		<legend>관리자</legend>
		<div>*관리자는 역할 또는 아이디로 설정할 수 있습니다.</div>
		<div class="Field">
			<div class="FieldName">Role</div>
			<div class="FieldValue">
				<asp:TextBox ID="AdministratorRoleNameTextBox" runat="server" ReadOnly="true" />
				<asp:DropDownList ID="RoleDropDownList" runat="server" AutoPostBack="true" 
					onselectedindexchanged="RoleDropDownList_SelectedIndexChanged" />
				(관리자역할은 하나만 설정할 수 있습니다.)
			</div>
		</div>
		<div class="Field">
			<div class="FieldName">Names</div>
			<div class="FieldValue">
				<asp:TextBox ID="AdministratorNamesTextBox" runat="server" />
				(관리자가 여러명일경우 콤마(,)로 구분)
			</div>
		</div>
		<div class="Field">
			<div class="FieldName">Email</div>
			<div class="FieldValue">
				<asp:TextBox ID="AdministratorEmailTextBox" runat="server" Columns="50" />
				<asp:RegularExpressionValidator ID="AdministratorEmailTextBoxRegularExpressionValidator"
					runat="server" ErrorMessage="*" ControlToValidate="AdministratorEmailTextBox" 
					ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" />
			</div>
			<div class="Clear"></div>
		</div>
		<div class="Field">
			<div class="FieldName">PublicationReport</div>
			<div class="FieldValue">
				<asp:CheckBox ID="PublicationReportCheckBox" runat="server" />
				<div>*게시보고. 게시판에 글, 댓글을 등록, 변경하는 경우 그 내용을 관리자 Email로 보고합니다. 이 기능은 서버에 SMTP서비스가 사용가능하도록 설정되어 있어야 합니다.</div>
			</div>
			<div class="Clear"></div>
		</div>
	</fieldset>

	<fieldset>
		<legend>폴더</legend>
		<div class="Field">
			<div class="FieldName">Root</div>
			<div class="FieldValue"><asp:Label ID="RootLabel" runat="server" /></div>
			<div class="Clear"></div>
		</div>
		<div class="Field">
			<div class="FieldName">FileFolder</div>
			<div class="FieldValue">Root <asp:TextBox ID="FileFolderTextBox" runat="server" Columns="50" Enabled="False" ReadOnly="True" /></div>
			<div class="Clear"></div>
		</div>
		<div class="Field">
			<div class="FieldName">MemberPictureFolder</div>
			<div class="FieldValue">Root <asp:TextBox ID="MemberPictureFolderTextBox" runat="server" Columns="50" Enabled="False" ReadOnly="True" /></div>
			<div class="Clear"></div>
		</div>
		<div class="Field">
			<div class="FieldName">ExceptionLogFolder</div>
			<div class="FieldValue">Root <asp:TextBox ID="ExceptionLogFolderTextBox" runat="server" Columns="50" Enabled="False" ReadOnly="True" /></div>
			<div class="Clear"></div>
		</div>
	</fieldset>

	<div class="Field"><asp:Button ID="UpdateSectionButton" runat="server" Text="확인" ValidationGroup="VWeb" onclick="UpdateSectionButton_Click" /></div>

	<hr />

	<fieldset>
		<legend>컨트롤셋팅</legend>
		<div class="Field">
			Property<asp:TextBox ID="PropertyTextBox" runat="server" ValidationGroup="ControlSetting" />
			<asp:RequiredFieldValidator ID="PropertyTextBoxRequiredFieldValidator" runat="server" ErrorMessage="*" ControlToValidate="PropertyTextBox" ValidationGroup="ControlSetting" />
			Value<asp:TextBox ID="ValueTextBox" runat="server" ValidationGroup="ControlSetting" />
			<asp:RequiredFieldValidator ID="ValueTextBoxRequiredFieldValidator" runat="server" ErrorMessage="*" ControlToValidate="ValueTextBox" ValidationGroup="ControlSetting" />
			<asp:Button ID="AddControlSettingButton" runat="server" Text="추가" 
				ValidationGroup="ControlSetting" onclick="AddControlSettingButton_Click" />
		</div>
		<div  class="Field">
			<asp:GridView ID="ControlSettingGridView" runat="server" 
				AutoGenerateColumns="false" DataKeyNames="Property" 
				onrowediting="ControlSettingGridView_RowEditing" 
				onrowcancelingedit="ControlSettingGridView_RowCancelingEdit" 
				onrowupdating="ControlSettingGridView_RowUpdating" 
				onrowdeleting="ControlSettingGridView_RowDeleting">
				<Columns>
					<asp:BoundField DataField="Property" HeaderText="Property" ReadOnly="true" />
					<asp:TemplateField HeaderText="Value">
						<ItemTemplate><%# Eval("Value") %></ItemTemplate>
						<EditItemTemplate><asp:TextBox ID="ValueTextBox" runat="server" Text='<%# Bind("Value") %>' /></EditItemTemplate>
					</asp:TemplateField>
					<asp:CommandField ButtonType="Button" HeaderText="" ShowSelectButton="false" ShowDeleteButton="true" ShowEditButton="true" />
				</Columns>
			</asp:GridView>
		</div>
	</fieldset>

</asp:Content>